/**
 * BoLe 智能HR招聘管理系统 JavaScript - 基于JH设计架构的统一前端
 * 处理多智能体交互、数据可视化、用户交互和API调用
 */

class HRDashboard {
    constructor() {
        // 动态获取当前页面的端口，避免硬编码
        this.apiBaseUrl = `${window.location.protocol}//${window.location.hostname}:${window.location.port}`; // HR系统API端点
        this.charts = {};
        this.currentFilters = {};
        this.currentPage = 1;
        this.pageSize = 20;
        this.totalPages = 1;
        this.totalCandidates = 0;
        this.isLoading = false;
        
        // 图表模态框管理
        this.modalChart = null;
        this.currentModalChartId = null;
        
        // 当前候选人数据
        this.currentCandidates = [];
        this.selectedCandidate = null;
        
        // 聊天历史
        this.chatHistory = [];
        
        // 用户偏好设置
        this.userPreferences = {
            theme: 'light',
            chartConfigs: {
                skillsChart: { type: 'doughnut' },
                experienceChart: { type: 'bar' },
                locationChart: { type: 'bar' },
                matchScoreChart: { type: 'line' }
            }
        };
        
        this.init();
    }
    
    async init() {
        console.log('初始化BoLe HR智能招聘系统...');
        
        // 初始化UI组件
        this.initializeTheme();
        this.initializeEventListeners();
        this.initializeTabs();
        this.initializeModals();
        this.initializeCharts();
        
        // 加载数据
        try {
            await this.loadOverviewData();
            await this.loadCandidatesData();
            await this.loadChartsData();
        } catch (error) {
            console.warn('数据加载失败，使用演示数据:', error);
            this.displayMockData();
        }
        
        console.log('✅ BoLe HR系统初始化完成');
    }
    
    // 初始化主题
    initializeTheme() {
        const themeSelect = document.getElementById('theme-select');
        const savedTheme = localStorage.getItem('hr-theme') || 'light';
        
        themeSelect.value = savedTheme;
        this.applyTheme(savedTheme);
        
        themeSelect.addEventListener('change', (e) => {
            this.applyTheme(e.target.value);
            localStorage.setItem('hr-theme', e.target.value);
        });
    }
    
    applyTheme(theme) {
        document.body.classList.toggle('dark-theme', theme === 'dark');
        this.userPreferences.theme = theme;
    }
    
    // 初始化事件监听器
    initializeEventListeners() {
        // AI聊天功能
        const chatInput = document.getElementById('chatInput');
        const sendChatBtn = document.getElementById('sendChatBtn');
        
        sendChatBtn.addEventListener('click', () => this.sendChatMessage());
        chatInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                this.sendChatMessage();
            }
        });
        
        // 筛选功能
        const applyFiltersBtn = document.getElementById('applyFiltersBtn');
        applyFiltersBtn.addEventListener('click', () => this.applyFilters());
        
        // 列表控制
        const refreshListBtn = document.getElementById('refreshListBtn');
        const sortBy = document.getElementById('sortBy');
        
        refreshListBtn.addEventListener('click', () => this.refreshCandidatesList());
        sortBy.addEventListener('change', () => this.sortCandidates());
        
        // 深度分析
        const startDeepAnalysisBtn = document.getElementById('startDeepAnalysisBtn');
        startDeepAnalysisBtn.addEventListener('click', () => this.startDeepAnalysis());
        
        // 图表放大按钮
        const expandBtns = document.querySelectorAll('.chart-expand-btn');
        expandBtns.forEach(btn => {
            btn.addEventListener('click', (e) => {
                const chartType = e.target.closest('.chart-expand-btn').getAttribute('data-chart');
                this.expandChart(chartType);
            });
        });
        
        // 设置和帮助按钮
        document.getElementById('settingsBtn').addEventListener('click', () => this.showSettings());
        document.getElementById('helpBtn').addEventListener('click', () => this.showHelp());
    }
    
    // 初始化标签页
    initializeTabs() {
        const tabButtons = document.querySelectorAll('.tab-button');
        const tabContents = document.querySelectorAll('.tab-content');
        
        tabButtons.forEach(button => {
            button.addEventListener('click', () => {
                const tabId = button.getAttribute('data-tab');
                
                // 移除所有active状态
                tabButtons.forEach(btn => btn.classList.remove('active'));
                tabContents.forEach(content => content.classList.remove('active'));
                
                // 激活当前标签页
                button.classList.add('active');
                document.getElementById(`${tabId}-tab`).classList.add('active');
                
                // 如果是图表标签页，重新调整图表大小
                if (tabId === 'analysis') {
                    setTimeout(() => {
                        Object.values(this.charts).forEach(chart => {
                            if (chart && chart.resize) chart.resize();
                        });
                    }, 100);
                }
            });
        });
    }
    
    // 初始化模态框
    initializeModals() {
        // 图表模态框
        const chartModal = document.getElementById('chartModal');
        const closeChartModal = document.getElementById('closeChartModal');
        
        closeChartModal.addEventListener('click', () => this.closeChartModal());
        chartModal.addEventListener('click', (e) => {
            if (e.target === chartModal) this.closeChartModal();
        });
        
        // 候选人详情模态框
        const candidateModal = document.getElementById('candidateModal');
        const closeCandidateModal = document.getElementById('closeCandidateModal');
        
        closeCandidateModal.addEventListener('click', () => this.closeCandidateModal());
        candidateModal.addEventListener('click', (e) => {
            if (e.target === candidateModal) this.closeCandidateModal();
        });
        
        // 模态框按钮事件
        document.getElementById('deepAnalyzeBtn').addEventListener('click', () => {
            this.closeCandidateModal();
            this.performDeepAnalysis(this.selectedCandidate);
        });
        
        document.getElementById('updateRecordBtn').addEventListener('click', () => {
            this.updateCandidateRecord(this.selectedCandidate);
        });
    }
    
    // 发送聊天消息
    async sendChatMessage() {
        const chatInput = document.getElementById('chatInput');
        const message = chatInput.value.trim();
        
        if (!message) return;
        
        // 添加用户消息到聊天历史
        this.addChatMessage('user', message);
        chatInput.value = '';
        
        // 显示加载状态
        this.showLoading(true);
        this.addChatMessage('assistant', '正在处理您的请求...', true);
        
        try {
            // 调用多智能体系统API
            const response = await fetch(`${this.apiBaseUrl}/api/chat`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    message: message,
                    user_id: 'hr_user_001'
                })
            });
            
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            
            const data = await response.json();
            
            // 移除加载消息
            this.removeChatLoadingMessage();
            
            // 添加AI回复
            this.addChatMessage('assistant', data.message || data.response);
            
            // 处理可能的数据更新
            if (data.ui_commands && data.ui_commands.length > 0) {
                this.processUICommands(data.ui_commands);
            }
            
            // 如果返回了候选人数据，更新列表
            if (data.analysis_results) {
                this.updateCandidatesDisplay(data.analysis_results);
            }
            
            this.showToast('success', '请求处理完成');
            
        } catch (error) {
            console.error('聊天请求失败:', error);
            this.removeChatLoadingMessage();
            this.addChatMessage('assistant', `抱歉，处理您的请求时出现了错误：${error.message}`);
            this.showToast('error', '请求处理失败');
        } finally {
            this.showLoading(false);
        }
    }
    
    // 添加聊天消息
    addChatMessage(sender, message, isLoading = false) {
        const chatHistory = document.getElementById('chatHistory');
        const messageDiv = document.createElement('div');
        
        messageDiv.className = `chat-message ${sender} ${isLoading ? 'loading' : ''}`;
        messageDiv.innerHTML = `
            <div class="message-content">
                ${sender === 'user' ? '<i class="fas fa-user"></i>' : '<i class="fas fa-robot"></i>'}
                <span>${message}</span>
            </div>
        `;
        
        chatHistory.appendChild(messageDiv);
        chatHistory.scrollTop = chatHistory.scrollHeight;
        
        // 保存到历史记录
        if (!isLoading) {
            this.chatHistory.push({ sender, message, timestamp: new Date() });
        }
    }
    
    // 移除加载消息
    removeChatLoadingMessage() {
        const loadingMessage = document.querySelector('.chat-message.loading');
        if (loadingMessage) {
            loadingMessage.remove();
        }
    }
    
    // 应用筛选条件
    async applyFilters() {
        const skills = document.getElementById('skillFilter').value;
        const experience = document.getElementById('experienceFilter').value;
        const location = document.getElementById('locationFilter').value;
        
        this.currentFilters = {
            skills: skills.split(',').map(s => s.trim()).filter(s => s),
            experience: experience,
            location: location.trim()
        };
        
        this.currentPage = 1; // 重置到第一页
        await this.loadCandidatesData();
        this.showToast('success', '筛选条件已应用');
    }
    
    // 加载概览数据
    async loadOverviewData() {
        try {
            // 这里可以调用实际的API
            const mockData = {
                totalCandidates: 156,
                matchedCandidates: 23,
                avgMatchScore: 75.8,
                topSkill: 'Python'
            };
            
            document.getElementById('totalCandidates').textContent = mockData.totalCandidates;
            document.getElementById('matchedCandidates').textContent = mockData.matchedCandidates;
            document.getElementById('avgMatchScore').textContent = `${mockData.avgMatchScore}%`;
            document.getElementById('topSkill').textContent = mockData.topSkill;
            
        } catch (error) {
            console.error('加载概览数据失败:', error);
        }
    }
    
    // 加载候选人数据
    async loadCandidatesData() {
        try {
            this.showLoading(true);
            
            // 模拟候选人数据
            const mockCandidates = [
                {
                    id: '001',
                    name: '张三',
                    skills: ['Python', 'JavaScript', 'React'],
                    experience: 3,
                    location: '北京',
                    education: '本科',
                    matchScore: 85.5
                },
                {
                    id: '002',
                    name: '李四',
                    skills: ['Java', 'Spring', 'MySQL'],
                    experience: 5,
                    location: '上海',
                    education: '硕士',
                    matchScore: 92.3
                },
                {
                    id: '003',
                    name: '王五',
                    skills: ['Vue.js', 'Node.js', 'MongoDB'],
                    experience: 2,
                    location: '深圳',
                    education: '本科',
                    matchScore: 78.1
                }
            ];
            
            this.currentCandidates = mockCandidates;
            this.displayCandidates(mockCandidates);
            this.updateCandidateSelector(mockCandidates);
            
        } catch (error) {
            console.error('加载候选人数据失败:', error);
            this.showToast('error', '候选人数据加载失败');
        } finally {
            this.showLoading(false);
        }
    }
    
    // 显示候选人列表
    displayCandidates(candidates) {
        const candidatesList = document.getElementById('candidatesList');
        
        if (candidates.length === 0) {
            candidatesList.innerHTML = `
                <div class="loading-message">
                    <i class="fas fa-search"></i>
                    暂无符合条件的候选人
                </div>
            `;
            return;
        }
        
        candidatesList.innerHTML = candidates.map(candidate => `
            <div class="candidate-card fade-in" onclick="hrDashboard.showCandidateDetail('${candidate.id}')">
                <div class="candidate-card-header">
                    <div class="candidate-name">${candidate.name}</div>
                    <div class="candidate-match-score">${candidate.matchScore}%</div>
                </div>
                <div class="candidate-details">
                    <div class="candidate-detail">
                        <i class="fas fa-briefcase"></i>
                        <span>${candidate.experience}年经验</span>
                    </div>
                    <div class="candidate-detail">
                        <i class="fas fa-map-marker-alt"></i>
                        <span>${candidate.location}</span>
                    </div>
                    <div class="candidate-detail">
                        <i class="fas fa-graduation-cap"></i>
                        <span>${candidate.education}</span>
                    </div>
                </div>
                <div class="candidate-skills">
                    <div class="candidate-skills-label">主要技能:</div>
                    <div class="skills-tags">
                        ${candidate.skills.map(skill => `<span class="skill-tag">${skill}</span>`).join('')}
                    </div>
                </div>
            </div>
        `).join('');
    }
    
    // 显示候选人详情
    showCandidateDetail(candidateId) {
        const candidate = this.currentCandidates.find(c => c.id === candidateId);
        if (!candidate) return;
        
        this.selectedCandidate = candidate;
        
        document.getElementById('candidateName').textContent = candidate.name;
        document.getElementById('candidateDetailContent').innerHTML = `
            <div class="candidate-detail-grid">
                <div class="detail-section">
                    <h4><i class="fas fa-user"></i> 基本信息</h4>
                    <div class="detail-item">
                        <span class="detail-label">姓名:</span>
                        <span class="detail-value">${candidate.name}</span>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">工作经验:</span>
                        <span class="detail-value">${candidate.experience}年</span>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">工作地点:</span>
                        <span class="detail-value">${candidate.location}</span>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">教育背景:</span>
                        <span class="detail-value">${candidate.education}</span>
                    </div>
                </div>
                <div class="detail-section">
                    <h4><i class="fas fa-code"></i> 技能信息</h4>
                    <div class="skills-display">
                        ${candidate.skills.map(skill => `<span class="skill-tag">${skill}</span>`).join('')}
                    </div>
                </div>
                <div class="detail-section">
                    <h4><i class="fas fa-chart-line"></i> 匹配度分析</h4>
                    <div class="match-score-display">
                        <div class="score-circle">
                            <span class="score-number">${candidate.matchScore}%</span>
                            <span class="score-label">综合匹配度</span>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        document.getElementById('candidateModal').style.display = 'block';
    }
    
    // 更新候选人选择器
    updateCandidateSelector(candidates) {
        const candidateSelect = document.getElementById('candidateSelect');
        candidateSelect.innerHTML = '<option value="">请选择候选人...</option>' +
            candidates.map(c => `<option value="${c.id}">${c.name} (${c.matchScore}%)</option>`).join('');
    }
    
    // 开始深度分析
    async startDeepAnalysis() {
        const candidateSelect = document.getElementById('candidateSelect');
        const candidateId = candidateSelect.value;
        
        if (!candidateId) {
            this.showToast('warning', '请先选择一个候选人');
            return;
        }
        
        const candidate = this.currentCandidates.find(c => c.id === candidateId);
        await this.performDeepAnalysis(candidate);
    }
    
    // 执行深度分析
    async performDeepAnalysis(candidate) {
        if (!candidate) return;
        
        this.showLoading(true);
        
        try {
            // 调用后端深度分析API
            const response = await fetch(`${this.apiBaseUrl}/api/hr/deep-analysis`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    candidate_id: candidate.id,
                    user_id: 'hr_user_001'
                })
            });
            
            const data = await response.json();
            this.displayDeepAnalysisResult(data);
            
            // 切换到深度分析标签页
            document.querySelector('[data-tab="deep-analysis"]').click();
            
            this.showToast('success', '深度分析完成');
            
        } catch (error) {
            console.error('深度分析失败:', error);
            this.displayMockDeepAnalysis(candidate);
            this.showToast('warning', '使用演示数据进行深度分析');
        } finally {
            this.showLoading(false);
        }
    }
    
    // 显示深度分析结果
    displayDeepAnalysisResult(data) {
        const resultContainer = document.getElementById('deepAnalysisResult');
        
        resultContainer.innerHTML = `
            <div class="deep-analysis-content">
                <div class="analysis-charts">
                    <div class="radar-chart-container">
                        <h4><i class="fas fa-radar-chart"></i> 能力雷达图</h4>
                        <canvas id="radarChart"></canvas>
                    </div>
                    <div class="bar-chart-container">
                        <h4><i class="fas fa-chart-bar"></i> 技能匹配度</h4>
                        <canvas id="skillMatchChart"></canvas>
                    </div>
                </div>
                <div class="analysis-report">
                    <h4><i class="fas fa-file-alt"></i> 分析报告</h4>
                    <div class="report-content">
                        ${data.report || '候选人综合评估报告将在此显示...'}
                    </div>
                </div>
            </div>
        `;
        
        // 创建雷达图和柱状图
        this.createRadarChart(data.radarData);
        this.createSkillMatchChart(data.skillMatchData);
    }
    
    // 显示演示深度分析
    displayMockDeepAnalysis(candidate) {
        const mockData = {
            radarData: {
                labels: ['技术能力', '项目经验', '沟通能力', '学习能力', '团队合作', '解决问题', '创新思维', '领导力'],
                datasets: [{
                    label: candidate.name,
                    data: [85, 75, 80, 90, 85, 88, 75, 70],
                    backgroundColor: 'rgba(102, 126, 234, 0.2)',
                    borderColor: 'rgba(102, 126, 234, 1)',
                    borderWidth: 2
                }]
            },
            skillMatchData: {
                labels: candidate.skills,
                datasets: [{
                    label: '匹配度(%)',
                    data: candidate.skills.map(() => Math.floor(Math.random() * 30) + 70),
                    backgroundColor: 'rgba(102, 126, 234, 0.8)'
                }]
            },
            report: `
                <h5>候选人: ${candidate.name}</h5>
                <p><strong>综合评分:</strong> ${candidate.matchScore}/100</p>
                <p><strong>核心优势:</strong></p>
                <ul>
                    <li>具备扎实的${candidate.skills[0]}技术基础</li>
                    <li>${candidate.experience}年相关工作经验</li>
                    <li>学习能力强，适应性好</li>
                </ul>
                <p><strong>面试建议:</strong></p>
                <ul>
                    <li>重点考察${candidate.skills.join('、')}相关技术深度</li>
                    <li>了解候选人的项目经验和解决问题的能力</li>
                    <li>评估团队合作和沟通能力</li>
                </ul>
            `
        };
        
        this.displayDeepAnalysisResult(mockData);
    }
    
    // 创建雷达图
    createRadarChart(data) {
        const ctx = document.getElementById('radarChart').getContext('2d');
        new Chart(ctx, {
            type: 'radar',
            data: data,
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        position: 'top',
                    }
                },
                scales: {
                    r: {
                        beginAtZero: true,
                        max: 100
                    }
                }
            }
        });
    }
    
    // 创建技能匹配图
    createSkillMatchChart(data) {
        const ctx = document.getElementById('skillMatchChart').getContext('2d');
        new Chart(ctx, {
            type: 'bar',
            data: data,
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        max: 100
                    }
                }
            }
        });
    }
    
    // 初始化图表
    initializeCharts() {
        // 技能分布图
        const skillsCtx = document.getElementById('skillsChartCanvas').getContext('2d');
        this.charts.skills = new Chart(skillsCtx, {
            type: 'doughnut',
            data: {
                labels: ['Python', 'JavaScript', 'Java', 'React', 'Vue.js', '其他'],
                datasets: [{
                    data: [25, 20, 18, 15, 12, 10],
                    backgroundColor: [
                        '#667eea', '#764ba2', '#f093fb', '#f5576c',
                        '#4facfe', '#00f2fe'
                    ]
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom'
                    }
                }
            }
        });
        
        // 经验分布图
        const expCtx = document.getElementById('experienceChartCanvas').getContext('2d');
        this.charts.experience = new Chart(expCtx, {
            type: 'bar',
            data: {
                labels: ['0-1年', '1-3年', '3-5年', '5-8年', '8年以上'],
                datasets: [{
                    label: '候选人数量',
                    data: [12, 35, 45, 28, 15],
                    backgroundColor: '#667eea'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false
            }
        });
        
        // 地域分布图
        const locCtx = document.getElementById('locationChartCanvas').getContext('2d');
        this.charts.location = new Chart(locCtx, {
            type: 'bar',
            data: {
                labels: ['北京', '上海', '深圳', '广州', '杭州', '其他'],
                datasets: [{
                    label: '候选人数量',
                    data: [45, 38, 32, 25, 18, 28],
                    backgroundColor: '#764ba2'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false
            }
        });
        
        // 匹配度分布图
        const matchCtx = document.getElementById('matchScoreChartCanvas').getContext('2d');
        this.charts.matchScore = new Chart(matchCtx, {
            type: 'line',
            data: {
                labels: ['0-20', '21-40', '41-60', '61-80', '81-100'],
                datasets: [{
                    label: '候选人数量',
                    data: [2, 8, 25, 65, 35],
                    borderColor: '#667eea',
                    backgroundColor: 'rgba(102, 126, 234, 0.1)',
                    fill: true
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false
            }
        });
    }
    
    // 展开图表
    expandChart(chartType) {
        const chartModal = document.getElementById('chartModal');
        const modalTitle = document.getElementById('modalChartTitle');
        const modalCanvas = document.getElementById('modalChartCanvas');
        
        const chartTitles = {
            skills: '技能分布详情',
            experience: '经验分布详情',
            location: '地域分布详情',
            matchScore: '匹配度分布详情'
        };
        
        modalTitle.textContent = chartTitles[chartType] || '图表详情';
        
        // 显示模态框
        chartModal.style.display = 'block';
        this.currentModalChartId = chartType;
        
        // 创建放大的图表
        setTimeout(() => {
            if (this.modalChart) {
                this.modalChart.destroy();
            }
            
            const originalChart = this.charts[chartType];
            if (originalChart) {
                const ctx = modalCanvas.getContext('2d');
                this.modalChart = new Chart(ctx, {
                    type: originalChart.config.type,
                    data: originalChart.config.data,
                    options: {
                        ...originalChart.config.options,
                        responsive: true,
                        maintainAspectRatio: false
                    }
                });
            }
        }, 100);
    }
    
    // 关闭图表模态框
    closeChartModal() {
        const chartModal = document.getElementById('chartModal');
        chartModal.style.display = 'none';
        
        if (this.modalChart) {
            this.modalChart.destroy();
            this.modalChart = null;
        }
        
        this.currentModalChartId = null;
    }
    
    // 关闭候选人模态框
    closeCandidateModal() {
        const candidateModal = document.getElementById('candidateModal');
        candidateModal.style.display = 'none';
        this.selectedCandidate = null;
    }
    
    // 更新候选人记录
    async updateCandidateRecord(candidate) {
        if (!candidate) return;
        
        this.showLoading(true);
        
        try {
            const updates = {
                status: '已联系',
                notes: '通过HR系统更新',
                last_contact: new Date().toISOString()
            };
            
            // 调用更新API
            const response = await fetch(`${this.apiBaseUrl}/api/hr/update-record`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    candidate_id: candidate.id,
                    updates: updates,
                    user_id: 'hr_user_001'
                })
            });
            
            if (response.ok) {
                this.showToast('success', '候选人记录已更新');
                this.closeCandidateModal();
            } else {
                throw new Error('更新失败');
            }
            
        } catch (error) {
            console.error('更新候选人记录失败:', error);
            this.showToast('error', '记录更新失败');
        } finally {
            this.showLoading(false);
        }
    }
    
    // 刷新候选人列表
    async refreshCandidatesList() {
        await this.loadCandidatesData();
        this.showToast('success', '候选人列表已刷新');
    }
    
    // 排序候选人
    sortCandidates() {
        const sortBy = document.getElementById('sortBy').value;
        const candidates = [...this.currentCandidates];
        
        candidates.sort((a, b) => {
            switch (sortBy) {
                case 'match_score':
                    return b.matchScore - a.matchScore;
                case 'name':
                    return a.name.localeCompare(b.name);
                case 'experience':
                    return b.experience - a.experience;
                default:
                    return 0;
            }
        });
        
        this.displayCandidates(candidates);
        this.showToast('info', '列表已重新排序');
    }
    
    // 处理UI命令
    processUICommands(commands) {
        commands.forEach(command => {
            switch (command.action) {
                case 'update_candidates':
                    this.displayCandidates(command.payload);
                    break;
                case 'show_analysis':
                    document.querySelector('[data-tab="analysis"]').click();
                    break;
                case 'highlight_candidate':
                    this.highlightCandidate(command.payload.candidate_id);
                    break;
                default:
                    console.log('未知UI命令:', command);
            }
        });
    }
    
    // 显示/隐藏加载状态
    showLoading(show) {
        const loadingOverlay = document.getElementById('loadingOverlay');
        loadingOverlay.style.display = show ? 'flex' : 'none';
        this.isLoading = show;
    }
    
    // 显示Toast通知
    showToast(type, message) {
        const toast = document.getElementById('toast');
        const toastIcon = document.getElementById('toastIcon');
        const toastMessage = document.getElementById('toastMessage');
        
        // 设置图标和样式
        const icons = {
            success: 'fas fa-check-circle',
            error: 'fas fa-exclamation-circle',
            warning: 'fas fa-exclamation-triangle',
            info: 'fas fa-info-circle'
        };
        
        toast.className = `toast ${type}`;
        toastIcon.className = icons[type] || icons.info;
        toastMessage.textContent = message;
        
        // 显示Toast
        toast.classList.add('show');
        
        // 自动隐藏
        setTimeout(() => {
            toast.classList.remove('show');
        }, 3000);
    }
    
    // 显示设置
    showSettings() {
        this.showToast('info', '设置功能即将上线');
    }
    
    // 显示帮助
    showHelp() {
        this.showToast('info', '帮助文档即将上线');
    }
    
    // 显示演示数据
    displayMockData() {
        console.log('使用演示数据');
        // 已在loadOverviewData和loadCandidatesData中实现
    }
}

// 全局实例
let hrDashboard;

// DOM加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    hrDashboard = new HRDashboard();
});

// 导出到全局作用域以供HTML事件调用
window.hrDashboard = hrDashboard;
